package com.itxiuyixiu.tools.common.converter;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.core.convert.converter.Converter;
import org.springframework.core.convert.converter.ConverterRegistry;
import org.springframework.lang.NonNull;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;

/**
 * @author 黄磊
 * @date 2020/1/23
 */
public class String2DateConverter implements Converter<String, Date> {
    @Override
    public Date convert(@NonNull String s) {
        Date date;
        try {
            if (s.matches("\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}")) {
                SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm");
                format.setTimeZone(TimeZone.getTimeZone("Asia/Shanghai"));
                date = format.parse(s);
            } else {
                date = null;
            }
        } catch (Exception e) {
            return null;
        }
        return date;
    }
}
